package com.itheima.rpc.netty.handler;

import com.itheima.rpc.data.RpcRequest;
import com.itheima.rpc.data.RpcResponse;
import com.itheima.rpc.spring.SpringBeanFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

@Slf4j
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest rpcRequest) throws Exception {
        RpcResponse rpcResponse = new RpcResponse();
        String requestId = rpcRequest.getRequestId();
        rpcResponse.setRequestId(requestId);

        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();

        try {
            //获取接口的bean实例
            Object bean = SpringBeanFactory.getBean(Class.forName(className));
            //获取目标方法
            Method method = bean.getClass().getMethod(methodName, parameterTypes);
            //执行目标方法
            Object result = method.invoke(bean, parameters);
            rpcResponse.setResult(result);
        } catch (Throwable e) {
            rpcResponse.setCause(e.getCause());
            throw new RuntimeException(e);
        } finally {
            ctx.channel().writeAndFlush(rpcResponse);
        }
    }
}
